<!--
 * @Author: Dorange.Wang
 * @Date: 2021-04-07 14:14:53
 * @LastEditors: wangming
 * @LastEditTime: 2021-12-22 16:55:02
 * @Description: file content
-->
<route>
{
  "meta":{
    "title": "序列号",
    "showMenu" :true,
    "serialNum": 55
  }
}
</route>
<template>
  <div style="height: calc(100% - 20px)">
    <el-row :gutter="24" class="pht100">
      <el-col
        :xs="12"
        :md="6"
        :lg="6"
        class="pht100 ovya ovhx"
        style="border-right: 1px solid #dcdfe6"
      >
        <ResizableGrid :handleStyle="{ transform: 'translateX(14px)' }">
          <div>
            <div class="custom-col-left-actions">
              <span style="float: left; margin-left: 8px; margin-top: 7px"
                >序列号分类</span
              >
              <el-button
                style="float: right; margin-top: 2px"
                type="text"
                @click="handleModalOpen(1, false)"
                >新建分类
              </el-button>
              <div>
                <el-input
                  placeholder="查询"
                  v-model="ruleSearchText"
                  clearable
                  class="input-with-select"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="onRuleSearch"
                  ></el-button>
                </el-input>
              </div>
            </div>
            <!--          :default-expanded-keys="[defaultSelectId]"-->
            <el-tree
              ref="tree"
              class="custom-tree pht100 mt15"
              :data="ruleTree"
              :expand-on-click-node="false"
              :default-expanded-keys="selectedKey ? [selectedKey] : []"
              node-key="id"
              highlight-current
              :current-node-key="selectedKey"
              @node-click="handleNodeClick"
            >
              <span class="custom-tree__node" slot-scope="{ node, data }">
                <span :title="data.ruleName" class="custom-tree__span">
                  <i
                    v-if="!node.expanded && data.level === 1"
                    class="el-icon-folder"
                  >
                  </i>
                  <i
                    v-if="node.expanded && data.level === 1"
                    class="el-icon-folder-opened"
                  ></i>
                  <i
                    v-if="data.level === 2 && data.ruleType === 'STATIC'"
                    class="el-icon-document"
                  ></i>
                  <i
                    v-if="data.level === 2 && data.ruleType === 'DYNAMIC'"
                    class="el-icon-document-checked"
                  ></i>

                  {{ data.ruleName }}</span
                >

                <el-dropdown
                  placement="bottom"
                  @command="onClickTypeDropdown($event, data)"
                >
                  <i class="el-icon-more" />
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-if="data.level === 1"
                      command="newStaticRule"
                      icon="el-icon-plus"
                      >新建静态规则</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="data.level === 1"
                      command="newDynamicRule"
                      icon="el-icon-plus"
                      >新建动态规则</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="data.level === 2 && data.ruleType === 'STATIC'"
                      command="newInstance"
                      icon="el-icon-plus"
                      >新建实例</el-dropdown-item
                    >
                    <el-dropdown-item command="edit" icon="el-icon-edit"
                      >编辑</el-dropdown-item
                    >
                    <el-dropdown-item command="delete" icon="el-icon-delete"
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu></el-dropdown
                >
              </span>
            </el-tree>
          </div>
        </ResizableGrid>
      </el-col>

      <el-col :span="18" class="pht100 ovya">
        <template v-if="!ruleTree.length">
          <p class="tc">请新建序列号分类</p>
        </template>
        <rule-config-form
          v-else
          ref="ruleConfigForm"
          :rule="ruleObj"
          :sectionList="sectionList"
          @reset="(id) => queryRule(id)"
        ></rule-config-form>
      </el-col>
      <serial-tree-form
        ref="SerialTreeForm"
        @ok="loadTreeData"
      ></serial-tree-form>
    </el-row>
  </div>
</template>

<script>
import { breadFirstTree, getTreeNodeById } from "@/utils/util";
import SerialTreeForm from "./__components__/serialTreeForm";
import RuleConfigForm from "./__components__/ruleConfigForm";
import ResizableGrid from "@/components/ResizableGrid";
import Empty from "@/components/Empty";
import { getTechserialnumTreelist,getTechserialnumInfo,deleteTechserialnum } from '@/apis/paas/TechSerialNumController.js'

export default {
  name: "SerialNum",
  components: {
    ResizableGrid,
    Empty,
    SerialTreeForm,
    RuleConfigForm,
  },
  data() {
    return {
      ruleSearchText: "",
      defaultSelectId: null,
      firstNodeId: null,
      ruleTree: [],
      ruleTreeB: [],
      selectedKey: undefined,
      selectedNode: null,
      isRuleSelected: true,
      expandedKeys: [],

      modalType: 1, // 类型:1分类 2规则 3实例 也是树节点的level字段
      isModalEdit: false,
      visible: false,
      treeLoading: false,
      rightLoading: false,
      ruleObj: {},
      sectionList: [],
      orgList: [],
      expandedOrg: [],
      currentOrg: undefined,
      loading: false,
      queryData: {},
      pageData: {
        pageSize: 10,
        pageNo: 1,
      },
      tableData: [],
      total: 0,
      userSelected: [],
    };
  },

  computed: {},

  created() {
    this.loadTreeData();
  },

  methods: {
    loadTreeData() {
      getTechserialnumTreelist().then((res) => {
        this.ruleTree = res || [];
        this.ruleTreeB = res || [];
        if (!this.ruleTree.length) return;
        breadFirstTree(
          this.ruleTree,
          (node) => {
            if (!this.selectedKey && node.level === 2) {
              this.selectedKey = node.id;
              this.$nextTick(() => {
                this.$refs.tree &&
                  this.$refs.tree.setCurrentKey(this.selectedKey);
              });
            }
            return true;
          },
          "children"
        );
        if (this.selectedKey) {
          this.onSelect(this.selectedKey);
          // this.expandedKeys = this.getDefaultExpandedKeys(this.defaultSelectId)
        }
      });
    },
    /**
     * 默认展开到选中的节点。如果没有选中的节点，则展开第一个节点
     */
    getDefaultExpandedKeys(selectedId) {
      const expandedKeys = [];
      if (selectedId) {
        breadFirstTree(
          this.ruleTree,
          (jn) => {
            if (jn.parentId === selectedId) {
              expandedKeys.push(jn.parentId);
            }
            if (jn.id === selectedId) {
              expandedKeys.push(jn.parentId);
            }
            return true;
          },
          "children"
        );
      } else {
        expandedKeys.push(this.defaultSelectId);
      }
      return expandedKeys;
    },

    queryRule(id) {
      if (!id) return;
      getTechserialnumInfo({
        id,
      })
        .then((res) => {
          this.ruleObj = res || {};
          this.sectionList = res.sectionList || [];
          this.$nextTick(() => {
            this.$refs.ruleConfigForm.recordSectionList = [...this.sectionList];
          });
        })
        .catch(() => {});
    },
    // nodes就是树形的最原始数据，query就是关键字，最后会返回满足条件的节点数组
    filter(nodes, query, key, ckey) {
      // 条件就是节点的title过滤关键字
      const predicate = function (node) {
        if (node[key].indexOf(query) > -1) {
          return true;
        }
        return false;
      };
      if (!(nodes && nodes.length)) {
        return [];
      }
      const newChildren = [];
      for (const node of nodes) {
        // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
        // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
        // 2. 自己本身符合条件
        const subs = this.filter(node[ckey], query, key, ckey);
        if (predicate(node)) {
          newChildren.push(node);
        } else if (subs && subs.length) {
          node[ckey] = subs;
          newChildren.push(node);
        }
      }
      return newChildren.length ? newChildren : [];
    },
    // 序列号树的查找
    onRuleSearch() {
      if (this.ruleSearchText) {
        this.ruleTree = this.filter(
          this.ruleTreeB,
          this.ruleSearchText,
          "ruleName",
          "children"
        );
        if (this.ruleTree.length > 0) {
          this.onSelect(this.ruleTree[0].id);
        }
      } else {
        this.loadTreeData();
      }
    },
    filterByRule(list, key, ckey, txt) {
      const ret = [];
      list.forEach((d) => {
        let obj = {};
        if (d[key].includes(txt)) {
          obj = d;
        }
        if (d[ckey].length) {
          obj[ckey] = this.filterByRule(d[ckey], key, ckey, txt);
        }
        ret.push(obj);
      });
      return ret;
    },
    // 选中分类节点
    onSelect(selectedKey, data) {
      const node =
        data || getTreeNodeById(this.ruleTree, selectedKey, "children");
      const id = node.id;
      this.selectedKey = id;
      this.selectedNode = node;
      this.queryRule(id);
    },
    handleNodeClick(node) {
      const id = node.id;
      this.selectedKey = id;
      this.selectedNode = node;
      this.$router.push({
        params: {
          id: id,
        },
      });
      this.queryRule(id);
    },
    onClickTypeDropdown(command, item) {
      switch (command) {
        case "newStaticRule":
          this.handleModalOpen(2, false, item, "STATIC");
          break;
        case "newDynamicRule":
          this.handleModalOpen(2, false, item, "DYNAMIC");
          break;
        case "newInstance":
          this.handleModalOpen(3, false, item);
          break;
        case "edit":
          this.handleModalOpen(item.level, true, item);
          break;
        case "delete": {
          if (item.children.length > 0) {
            if (item.parentId) {
              this.$notify({
                title: "警告",
                message: "规则下有实例，需先删除实例",
                type: "warning",
              });
            } else {
              this.$notify.warning({
                title: "警告",
                message: "分类下有规则，需先删除规则",
              });
            }
            return;
          }

          let name = "规则";
          if (item.level === 1) {
            name = "分类";
          } else if (item.level === 3) {
            name = "实例";
          }

          this.$confirm(`确定删除该${name}吗`, "警告", {
            type: "warning",
            center: true,
          }).then((res) => {
            deleteTechserialnum([item.id]).then((res) => {
              this.$message.success("操作成功");
              this.loadTreeData();
              if (this.selectedKey === item.id) {
                this.selectedKey = null;
                this.ruleObj = {};
              }
            });
          });
          break;
        }
        default:
      }
    },
    // 新建编辑树的数据
    handleModalOpen(type, isEdit, record = {}, ruleType) {
      const dialog = this.$refs.SerialTreeForm;
      dialog.visible = true;
      dialog.modalType = type;
      dialog.isModalEdit = isEdit;
      dialog.parentId = record.id;
      if (isEdit) {
        dialog.editForm({ ...record });
      } else {
        dialog.addForm({ ruleType });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.user-status-badge {
  margin-top: 12px;
  margin-right: 5px;
}

.org-name-tag {
  margin-top: 5px;
  margin-right: 5px;
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
  color: #909399;
  padding: 0 8px;
  line-height: 22px;
  box-sizing: border-box;
  border-radius: 4px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-inline-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
</style>
